#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

void Usage(const std::string& proc)
{
    std::cout << "you can use " << proc << " ip port" << std::endl;
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    //1.创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cout << "sock error " << std::endl;
        return 2;
    }
    //2.发起连接
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cout << "connect error " << std::endl;
        return 3;
    } 
    //3.使用服务
#define NUM 2048
    while(true)
    {
        std::string s;
        std::cout << "请输入# ";
        std::cin >> s;
        write(sock, s.c_str(), s.length());

        char buffer[NUM] = {0};
        ssize_t ret = read(sock, buffer, sizeof(buffer));
        if(ret > 0)
        {
            std::cout << "server# " << buffer << std::endl;
        }
    }
    
    return 0;
}